﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YY.Admin.Services.Service.Config
{
    public class SysConfigService : ISysConfigService, ISingletonDependency
    {
        private readonly ISysCacheService _sysCacheService;
        private readonly ISqlSugarClient _dbContext;
        public SysConfigService(
            ISysCacheService sysCacheService,
            ISqlSugarClient dbContext) 
        {
            _sysCacheService= sysCacheService;
            _dbContext= dbContext;
        }
        public async Task<T> GetConfigValue<T>(string code)
        {
            if (string.IsNullOrWhiteSpace(code)) return default;

            var value = _sysCacheService.Get<string>($"{CacheConst.KeyConfig}{code}");
            if (string.IsNullOrEmpty(value))
            {
                value = (await _dbContext.Queryable<SysConfig>().FirstAsync(u => u.Code == code))?.Value;
                _sysCacheService.Set($"{CacheConst.KeyConfig}{code}", value);
            }
            if (string.IsNullOrWhiteSpace(value)) return default;
            return (T)Convert.ChangeType(value, typeof(T));
        }
    }
}
